package Service;

import Dao.UserDao;
import Model.User;
import Utils.DaoFactory;
import Utils.SHA256Utils;
import Utils.SaltGenerateUtil;

import javax.servlet.http.HttpSession;
import java.io.UnsupportedEncodingException;
import java.security.NoSuchAlgorithmException;
import java.util.List;

/**
 * @author zyp
 * date 2022-03-08
 */
public class UserServiceImpl implements UserService {
    UserDao userDao = DaoFactory.getUserDao();

    @Override
    public boolean register(User user) {
        //1.生成salt
        String salt = SaltGenerateUtil.getRandomString(16);
        //2.将用户输入的明文和字符串进行组合 组合逻辑 salt+“abcdef123456”+明文
        String saltAndPwd = salt + "abcdef123456" + user.getPassword();
        //3.应该把saltAndPwd这个字符串交给哈希函数进行处理，得到hash值\
        String hashPwd = SHA256Utils.getSHA256StrJava(saltAndPwd);
        //4.把盐和hash值设置进user对象
        user.setSalt(salt);
        user.setPassword(hashPwd);
        if (userDao.addUser(user) == 1) {
            return true;
        } else {
            return false;
        }
    }

    @Override
    public boolean login(User inputUser, HttpSession httpSession) {
        //1.根据用户输入的用户名，去找数据库里面的user对象
        User selectUser = userDao.findUserByUsername(inputUser);
        //2.找到user对象以后，从user对象里面把salt取出来，然后和用户输入的密码进行组合
        //3.比较输入密码和数据库密码的hash值，如果一致表示登录成功
        if (SHA256Utils.getSHA256StrJava(selectUser.getSalt() + "abcdef123456" + inputUser.getPassword()).equals(selectUser.getPassword())) {
            httpSession.setAttribute("loginUser", selectUser);
            return true;
        }

        return false;
    }

    @Override
    public boolean updateUser(User user) {
        return false;
    }

    @Override
    public boolean deleteUser(int id) {
        return false;
    }

    @Override
    public User findUserByUsername(String username) {
        return null;
    }

    @Override
    public List<User> findAllUsers() {
        return null;
    }

    @Override
    public User findUserByUserId(int id) {
        return null;
    }
}
